package com.itboye.jinpuyiyuan.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.LoginOrRegisterActivity;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.loadingutil.LoadingDialog;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;



/**
 * 继承自该类的Activity不需要使用findViewById(),只需要把控件声明称类内全局的，</br>并且和activity对应的布局中的id的名字相同，这样setContentView后就可以直接使用控件了，</br>
 * 同时不需要为控件设置clickListener， 直接在类上implements onClickListener,</br>
 * 并在activity中 重写onClick()方法，当点击控件时即可自动调用onClick()方法
 * <p>
 * </br>参考
 * 沉浸式状态栏 ，设置状态栏颜色使用setStatusBarColor，参数为颜色资源id，默认为橙色状态栏
 *
 * @author Young
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class BaseActivity extends FragmentActivity implements View.OnClickListener {

    private View statusBar;
    private LinearLayout container;
    LoadingDialog progressDialog = null;
    /**
     * 是否开启  右划关闭activity 手势，默认开启
     */
    private boolean isGestureOpen = true;

    @SuppressLint("InlinedApi")
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        MyApplication.getInstance().addActivity(this);

        PushAgent.getInstance(getApplication()).onAppStart();

        progressDialog = new LoadingDialog();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//安卓布局 延伸到状态栏
                Window window = getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                        | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

//                window.setFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
//                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// 虚拟导航栏透明
                 window.setFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                  WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.setStatusBarColor(0xFF2E9FCD);
                window.setNavigationBarColor(Color.TRANSPARENT);
            }

            statusBar = new View(this);
            ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight());
            statusBar.setLayoutParams(param);
//			setStatusBarColor(R.color.main_color);

            container = new ViewContainer(getApplicationContext());
            container.setOrientation(LinearLayout.VERTICAL);
            //	container.addView(statusBar);//加

            //App.getInstance().addActivity(this);
        }
//		PushAgent.getInstance(getApplicationContext()).onAppStart();
    }

//    @Override
//    public void startActivityForResult(Intent intent, int requestCode) {
//
//        super.startActivityForResult(intent, requestCode);
////		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
////			overridePendingTransition(R.anim.anim_enter_open_activity, R.anim.anim_exit_open_activity);
////		}
//    }
//
//
//    @SuppressLint("NewApi")
//    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
//        super.startActivityForResult(intent, requestCode, options);
////		overridePendingTransition(R.anim.anim_enter_open_activity, R.anim.anim_exit_open_activity);
//    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
//		overridePendingTransition(R.anim.anim_enter_finish_activity, R.anim.anim_exit_finish_activity);
    }

    /**
     * 设置状态栏颜色，
     *
     * @param color 颜色资源id， 如 R.color.orange</br>
     *              0 黑色
     */
    protected void setStatusBarColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (color == 0) {
                statusBar.setBackgroundColor(Color.BLACK);
            } else {
                statusBar.setBackgroundColor(getResources().getColor(color));
            }

        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
//		MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
//		MobclickAgent.onPause(this);
    }

    /**
     * 显示进度对话框,带有消息 flag 是否可以取消
     */
    @SuppressLint("NewApi")
    public void showProgressDialog(String message, boolean flag) {
        if (progressDialog == null)
            return;
        setProgressDialogMessage(message);

        progressDialog.show(getFragmentManager(), message);
        progressDialog.setCancelable(flag);

    }

    /**
     * 设置进度对话框消息
     *
     * @param message
     */
    public void setProgressDialogMessage(String message) {
        progressDialog.setMsg(message);
    }

    /**
     * 关闭进度对话框
     */
    @SuppressLint("NewApi")
    public void closeProgressDialog() {
        if (progressDialog == null)
            return;
        if (progressDialog.getDialog().isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }

            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置  
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (ev.getX() > left && ev.getX() < right
                    && ev.getY() > top && ev.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件  
                return false;
            } else {
                return true;
            }
        }
        return false;

    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            LayoutInflater.from(this).inflate(layoutResID, container, true);
            setContentView(container);

        } else {
            super.setContentView(layoutResID);
        }
        smartInject();

    }



    /**
     * 设置是否允许屏幕左侧 快速 右划关闭activity，默认允许
     *
     * @param b
     */
    protected void isGestureSensitive(boolean b) {
        isGestureOpen = b;
    }

    private void smartInject() {

        try {
            Class<? extends Activity> clz = getClass();

            while (clz != BaseActivity.class) {

                Field[] fs = clz.getDeclaredFields();
                Resources res = getResources();
                String packageName = getPackageName();
                for (Field field : fs) {
                    if (!View.class.isAssignableFrom(field.getType())) {
                        continue;
                    }
                    int viewId = res.getIdentifier(field.getName(), "id", packageName);
                    if (viewId == 0)
                        continue;
                    field.setAccessible(true);
                    try {
                        View v = findViewById(viewId);
                        field.set(this, v);
                        Class<?> c = field.getType();
                        Method m = c.getMethod("setOnClickListener", View.OnClickListener.class);
                        m.invoke(v, this);
                    } catch (Throwable e) {
                    }
                    field.setAccessible(false);

                }

                clz = (Class<? extends Activity>) clz.getSuperclass();

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    @Override
    public void onClick(View view) {

    }

    /**
     * 屏幕左侧右划返回容器 ,
     *
     * @author Young
     */
    private class ViewContainer extends LinearLayout {

        private int leftMargin;
        private VelocityTracker tracker;
        private float startX;
        private float startY;

        public ViewContainer(Context context) {
            super(context);
//			leftMargin= DensityUtil.dip2px(35);

        }


        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            if (isGestureOpen == false) {
                return super.dispatchTouchEvent(ev);
            }
            switch (ev.getAction()) {
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    //当满足下面条件时 视为 右划关闭手势
                    //起始按压位置x坐标小与leftMargin&& 向右滑动                       &&           向右滑动距离    >   竖直方向距离
                    if (startX < leftMargin && ev.getRawX() > startX && ev.getRawX() - startX > Math.abs(ev.getRawY() - startY)) {
                        //速度大于2500时关闭activity
                        tracker.computeCurrentVelocity(1000);
                        if (tracker.getXVelocity() > 2500) {
                            finish();
                        }

                    }

                    tracker.recycle();
                    break;

                case MotionEvent.ACTION_DOWN:
                    startX = ev.getRawX();
                    startY = ev.getRawY();
                    tracker = VelocityTracker.obtain();
                    tracker.addMovement(ev);
                    break;
                case MotionEvent.ACTION_MOVE:
                    tracker.addMovement(ev);
                    break;
            }


            return super.dispatchTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (isGestureOpen == false) {
                return super.onTouchEvent(event);
            }
            return true;
        }

    }

    private final String TAG = "MPermissions";
    private int REQUEST_CODE_PERMISSION = 0x00099;

    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionSuccess(REQUEST_CODE_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
        }
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }


    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
                if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                 //   MyApplication.instatnce.initLocation();
                }

            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
                showTipsDialog();

            }
        }
    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {
        Log.d(TAG, "获取权限成功=" + requestCode);

    }

    /**
     * 权限获取失败
     *
     * @param requestCode
     */
    public void permissionFail(int requestCode) {
        Log.d(TAG, "获取权限失败=" + requestCode);
    }
    /**
     * 设置状态栏高度
     * @param
     */
    public void setStatusBarHeight(View view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = getStatusBarHeight();
        view.setLayoutParams(params);
    }

    /**
     * 设置底部操作栏高度
     * @param
     */
    public void setNavigationBarHeight(View view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        Resources resources = getResources();

        int resourceId=resources.getIdentifier("navigation_bar_height","dimen","android");

        params.height = resources.getDimensionPixelSize(resourceId);
        view.setLayoutParams(params);
    }

    /**
     * 获取状态栏高度
     * @return
     */
    protected int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

//    /**
//     * 获取操作栏高度
//     * @return
//     */
//    protected int getStatusBarHeight() {
//        int result = 0;
//        int resourceId = getResources().getIdentifier("status_bar_height",
//                "dimen", "android");
//        if (resourceId > 0) {
//            result = getResources().getDimensionPixelSize(resourceId);
//        }
//        return result;
//    }

    public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class
            .getName() + "_unknown";
    /**
     * //     * @param data
     *
     * @return 2016-4-23 hebidu
     */
    public ResultEntity handlerError(Object data) {
        ResultEntity result = (ResultEntity) data;
        if (result == null) {
            result = new ResultEntity("-1", "数据格式错误!~", data);
            return result;
        }

//        if (result.hasError()) {
//            MAlert.alert(result.getMsg(), Gravity.TOP);
//            result.setEventType(EVENT_TYPE_UNKNOWN);
//            return result;
//        }

        return result;
    }


}
